package com.example.tys.baseapplication.NetModel.okhttp;

import android.support.annotation.NonNull;
import android.support.annotation.Nullable;

import java.io.InputStream;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.KeyManager;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.X509TrustManager;

/**
 * OkHttpsSslUtils.SslParams sslParams = OkHttpsSslUtils.createdSslParams(
 * new InputStream[]{getAssets().open("dss_thrift.cer", AssetManager.ACCESS_RANDOM)},
 * null, null);
 * .......
 * .sslSocketFactory(sslParams.sSLSocketFactory, sslParams.trustManager)
 * <p>
 * 注意：
 * 1.访问 https + 私有证书，必须设置ssl参数(服务器证书)，否则出现ssl异常
 * 2.当设置了某个地址的ssl参数后(e.https://192.168.0.101:8443)
 * 访问其他https地址(e.https://www.baidi.com)时将出现ssl异常。
 *
 * @author tys
 * @see #createdSslParams(InputStream[], InputStream, String)
 * @see #createdSslParams(InputStream, String, InputStream, String)
 */
public class OkHttpsSslUtils {

    private static TrustManager[] prepareTrustManager(InputStream... certificates) {
        TrustManager[] trustManagers = null;
        if (certificates == null || certificates.length == 0) {
            return null;
        }
        try {
            CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
            KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
            keyStore.load(null);
            int index = 0;
            for (InputStream certificate : certificates) {
                String certificateAlias = Integer.toString(index++);
                keyStore.setCertificateEntry(certificateAlias, certificateFactory.generateCertificate(certificate));
                certificate.close();
            }
            TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
            trustManagerFactory.init(keyStore);
            trustManagers = trustManagerFactory.getTrustManagers();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return trustManagers;
    }

    private static TrustManager[] prepareTrustManagerBks(InputStream certificates, String passWord) {
        TrustManager[] trustManagers = null;
        if (certificates == null) {
            return null;
        }
        try {
            KeyStore keyStore = KeyStore.getInstance("BKS");
            keyStore.load(certificates, passWord.toCharArray());
            TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
            trustManagerFactory.init(keyStore);
            trustManagers = trustManagerFactory.getTrustManagers();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return trustManagers;
    }


    private static KeyManager[] prepareKeyManager(InputStream bksFile, String password) {
        try {
            if (bksFile != null && password != null) {
                KeyStore clientKeyStore = KeyStore.getInstance("BKS");
                clientKeyStore.load(bksFile, password.toCharArray());
                KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
                keyManagerFactory.init(clientKeyStore, password.toCharArray());
                return keyManagerFactory.getKeyManagers();
            }
            return null;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    private static X509TrustManager chooseTrustManager(TrustManager[] trustManagers) {
        for (TrustManager trustManager : trustManagers) {
            if (trustManager instanceof X509TrustManager) {
                return (X509TrustManager) trustManager;
            }
        }
        return null;
    }

    private static class MyTrustManager implements X509TrustManager {
        private X509TrustManager defaultTrustManager;
        private X509TrustManager localTrustManager;

        MyTrustManager(X509TrustManager localTrustManager) throws NoSuchAlgorithmException, KeyStoreException {
            TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
            trustManagerFactory.init((KeyStore) null);
            this.defaultTrustManager = OkHttpsSslUtils.chooseTrustManager(trustManagerFactory.getTrustManagers());
            this.localTrustManager = localTrustManager;
        }

        @Override
        public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            //
        }

        @Override
        public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            try {
                this.defaultTrustManager.checkServerTrusted(chain, authType);
            } catch (CertificateException var4) {
                this.localTrustManager.checkServerTrusted(chain, authType);
            }
        }

        @Override
        public X509Certificate[] getAcceptedIssuers() {
            return new X509Certificate[0];
        }
    }

    private static class UnSafeTrustManager implements X509TrustManager {
        protected UnSafeTrustManager() {
        }

        @Override
        public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
        }

        @Override
        public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
        }

        @Override
        public X509Certificate[] getAcceptedIssuers() {
            return new X509Certificate[0];
        }
    }

    /**
     * ssl校验
     *
     * @param certificates service证书 非bks文件(.cer, .keystore)
     * @param bksFile      client(bks文件)
     * @param password     client(bks文件)密码
     * @return
     */
    public static SslParams createdSslParams(@NonNull InputStream[] certificates, @Nullable InputStream bksFile, @Nullable String password) {
        SslParams sslParams = new SslParams();
        try {
            TrustManager[] trustManagers = OkHttpsSslUtils.prepareTrustManager(certificates);
            KeyManager[] keyManagers = OkHttpsSslUtils.prepareKeyManager(bksFile, password);
            SSLContext sslContext = SSLContext.getInstance("TLS");
            X509TrustManager trustManager;
            if (trustManagers != null) {
                trustManager = new OkHttpsSslUtils.MyTrustManager(OkHttpsSslUtils.chooseTrustManager(trustManagers));
            } else {
                trustManager = new OkHttpsSslUtils.UnSafeTrustManager();
            }
            sslContext.init(keyManagers, trustManagers, null);
            sslParams.sSLSocketFactory = sslContext.getSocketFactory();
            sslParams.trustManager = trustManager;
            return sslParams;
        } catch (NoSuchAlgorithmException | KeyManagementException | KeyStoreException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * ssl校验
     *
     * @param bksCertificates    server证书(bks文件)
     * @param bksCertificatesPwd server证书(bks文件)对应密码
     * @param bksFile            client(bks文件)
     * @param password           client(bks文件)对应密码
     * @return
     */
    public static SslParams createdSslParams(@NonNull InputStream bksCertificates, @NonNull String bksCertificatesPwd,
                                             @Nullable InputStream bksFile, @Nullable String password) {
        SslParams sslParams = new SslParams();
        try {
            TrustManager[] trustManagers = OkHttpsSslUtils.prepareTrustManagerBks(bksCertificates, bksCertificatesPwd);
            KeyManager[] keyManagers = OkHttpsSslUtils.prepareKeyManager(bksFile, password);
            SSLContext sslContext = SSLContext.getInstance("TLS");
            X509TrustManager trustManager;
            if (trustManagers != null) {
                trustManager = new OkHttpsSslUtils.MyTrustManager(OkHttpsSslUtils.chooseTrustManager(trustManagers));
            } else {
                trustManager = new OkHttpsSslUtils.UnSafeTrustManager();
            }
            sslContext.init(keyManagers, trustManagers, null);
            sslParams.sSLSocketFactory = sslContext.getSocketFactory();
            sslParams.trustManager = trustManager;
            return sslParams;
        } catch (NoSuchAlgorithmException | KeyManagementException | KeyStoreException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static class SslParams {
        SSLSocketFactory sSLSocketFactory;
        X509TrustManager trustManager;
    }

    private class UnSafeHostnameVerifier implements HostnameVerifier {
        private UnSafeHostnameVerifier() {
        }

        @Override
        public boolean verify(String hostname, SSLSession session) {
            return true;
        }
    }
}
